package com.itheima.service.impl;

import com.itheima.common.utils.SMSUtils;
import com.itheima.pojo.Member;
import com.itheima.service.CalidateCodeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Random;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
public class CalidateCodeServiceImpl implements CalidateCodeService {
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 手机号快速登录发送验证码
     */
    @Override
    public boolean send4Login(String telephone) {
        //生成验证码
        String code = generateCode();
        log.info("验证码为：{}", code);
        //调用方法发送验证码
        SMSUtils.sendMessage(SMSUtils.VALIDATE_CODE,telephone,code);
        //存储code和电话
        redisTemplate.opsForValue().set(code, telephone,5, TimeUnit.MINUTES);
        //业务成功执行返回true
        return true;
    }
    /**
     * 生成验证码
     * @param
     * @return 生成的验证码
     */
    private static String generateCode() {
        Random random = new Random();
        StringBuilder code = new StringBuilder();
        for (int i = 0; i < 6; i++) {
            code.append(random.nextInt(10));
        }
        return code.toString();
    }
}
